import {login, logout, getUserInfo} from '@/api/user'
import {setToken, getToken} from '@/libs/util'
import userimg from '@/assets/images/user.png';
import {Message} from 'iview'

export default {
    state: {
        userName: '',
        userId: '',
        avatorImgPath: userimg,
        token: getToken(),
        access: ''
    },
    mutations: {
        setAvator(state, avatorPath) {
            state.avatorImgPath = avatorPath
        },
        setUserId(state, id) {
            state.userId = id
        },
        setUserName(state, name) {
            state.userName = name
        },
        setAccess(state, access) {
            state.access = access
        },
        setToken(state, token) {
            state.token = token
            setToken(token)
        }
    },
    actions: {
        // 登录
        handleLogin({commit}, {username, password}) {
            username = username.trim()
            return new Promise((resolve, reject) => {
                login({
                    username,
                    password
                }).then(res => {
                    console.info(res)
                    if (res.code == 20000) {
                        commit('setToken', res.data)
                        //commit('setUserId', res.data.userId)
                        resolve()
                    }else {
                        Message.error({
                            content: res.message,
                            duration: 3
                        })
                    }
                }).catch(err => {
                    reject(err)
                })
            })
        },
        // 退出登录
        handleLogOut({state, commit}) {
            return new Promise((resolve, reject) => {
                // logout(state.token).then(() => {
                //     commit('setToken', '')
                //     commit('setAccess', [])
                //     resolve()
                // }).catch(err => {
                //     reject(err)
                // })
                // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
                commit('setToken', '')
                commit('setAccess', [])
                resolve()
            })
        },
        // 获取用户相关信息
        getUserInfo({state, commit}) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    const data = res.data
                    //commit('setAvator', data.avator)
                    commit('setUserName', data.name)
                    commit('setUserId', data.id)
                    commit('setAccess', data.access)
                    resolve(data)
                }).catch(err => {
                    reject(err)
                })
            })
        }
    }
}
